package common.parser;

import com.han.http.client.exception.NullContentMatchedException;
import com.han.http.util.Regex;
import common.util.FileOperator;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static com.han.http.util.Print.printlnInfo;

/**
 * @author: Han
 * @date: 2018/8/21 11:11
 * @dscription: 解析细节列表
 */
public class DetailListParser {

    public static Map<String, String> getDetailUrl(String jsonStr, String urlStr) {
        String host = "";
        try {
            host = new URL(urlStr).getHost();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>(20);
        String startFlag = "<tr>";
        String endFlag = "</tr>";
        while (jsonStr.contains(startFlag)) {
            int start = jsonStr.indexOf(startFlag);
            int end = jsonStr.indexOf(endFlag) + endFlag.length();
            try {
                String tr = jsonStr.substring(start, end);
                String url = Regex.matchString(tr, "(?<=a href=\")((?!\\s).)*(?=\")");
                String title = Regex.matchString(tr, "(?<=>)((?!>).)*(?=</a>)");
                if (url.length() < 6 || title.length() < 6) {
                    throw new NullContentMatchedException();
                }
                if (url.startsWith("./")) {
                    url = url.replace("./", "/");
                    urlStr = urlStr.substring(0, urlStr.lastIndexOf("/"));
                    url = urlStr + url;
                }
                if (url.startsWith("../")) {
                    url = url.replace("../", "");
                    url = "/" + url;
                }
                if (url.startsWith("/")) {
                    url = host + url;
                }
                map.put(url, title);
                /*printlnInfo(url + " " + title);
                DetailEntity entity = new DetailEntity(url, title, 0);
                detailEntityList.add(entity);*/
            } catch (Exception ignore) {
            } finally {
                jsonStr = jsonStr.substring(end);
            }
        }
        return map;
    }

    public static void main(String... args) {
        printlnInfo(getDetailUrl(FileOperator.readTest(), "http://www.sczj.gov.cn/zzjg/lyx_4/ldhd_l/index_9.html"));
    }
}
